package host.skiree.nettydemo.server.service.impl;

import host.skiree.nettydemo.message.ChatRequestMessage;
import host.skiree.nettydemo.message.ChatResponseMessage;
import host.skiree.nettydemo.message.Message;
import host.skiree.nettydemo.server.dto.factory.UserChannelFactory;
import host.skiree.nettydemo.server.service.MessageHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

/**
 * @author gcl
 * @date 2022/9/20 9:40
 */
public class Chat implements MessageHandler {

    @Override
    public void handleMessage(ChannelHandlerContext ctx, Message message) {
        ChatRequestMessage chatMessage = (ChatRequestMessage) message;
        String toName = chatMessage.getTo();
        if ( toName.equals(chatMessage.getFrom()) ){
            ctx.channel().writeAndFlush(new ChatResponseMessage(false, "不能给自己发送私聊"));
            return;
        }
        Channel channel = UserChannelFactory.getInstance().getChannel(toName);
        if (channel == null){
            ctx.channel().writeAndFlush(new ChatResponseMessage(false, "对方不在线或不存在"));
        }else {
            channel.writeAndFlush(new ChatResponseMessage(chatMessage.getFrom(), chatMessage.getContent()));
        }

    }

}
